<!-- 活动详情 -->
<template>
  <div class="promotions_details">
    <el-container class="base_details_container">
      <BackTitleView :title="title" />
      <el-main>
        <el-tabs v-model="activeName" type="border-card" class="base_details_tabs">
          <el-tab-pane name="basic">
            <template #label>
              <el-badge>
                <span>基本信息</span>
              </el-badge>
            </template>
            <div class="content">
              <div class="base_details_title">基本信息</div>
              <div class="base_details_content_second">
                <el-form ref="basicFormRef" :model="basicForm" :disabled="readOnly" :rules="basicRules"
                  label-width="100px" class="base_details_form">
                  <el-form-item label="活动名称" prop="name">
                    <el-input v-model="basicForm.name" placeholder="请输入" />
                  </el-form-item>
                  <el-form-item label="活动时间" prop="date">
                    <div class="base_details_date_picker">
                      <el-date-picker v-model="basicForm.date" type="daterange" range-separator="~"
                        start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD 00:00:00"
                        :disabled-date="setDisableDate" />
                    </div>
                  </el-form-item>
                  <el-form-item label="活动列表图" prop="itemPic">
                    <UploadPicture v-model="basicForm.itemPic" :limit="1" :disabled="readOnly" :fileSize="$.imgFileSize()" />
                  </el-form-item>
                  <el-form-item label="活动封面" prop="mainPic">
                    <UploadPicture v-model="basicForm.mainPic" :limit="1" :disabled="readOnly"
                      :imgSize="$.marketingSize()" :fileSize="$.imgFileSize()" />
                  </el-form-item>
                  <el-form-item label="活动简介" prop="intro">
                    <el-input v-model="basicForm.intro" :rows="3" type="textarea" resize="none" />
                  </el-form-item>
                </el-form>
              </div>
              <div class="base_details_title">优惠设置</div>
              <div class="base_details_content_second">
                <el-form ref="discountsFormRef" :model="basicForm" :disabled="readOnly" :rules="basicRules"
                  label-width="100px" class="base_details_form">
                  <el-form-item label="优惠形式" prop="moneyType">
                    <el-radio-group v-model="basicForm.moneyType">
                      <el-radio v-for="(item, index) in moneyTypeOptions" :key="index" :label="item.value">{{ item.label
                      }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item v-if="basicForm.moneyType === '1010001'" label="优惠内容" prop="moneyOff">
                    <div class="money_box">
                      <span>满</span>
                      <el-input v-model="basicForm.moneyOff.limitMoney" placeholder="请输入" />
                      <span>元，减</span>
                      <el-input v-model="basicForm.moneyOff.money" placeholder="请输入" />
                      <span>元</span>
                    </div>
                  </el-form-item>
                  <el-form-item v-else label="优惠内容" prop="discountMoney">
                    <el-input v-model="basicForm.discountMoney" placeholder="请输入折扣，例如：9.8" />
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane name="spec">
            <template #label>
              <el-badge>
                <span>关联产品</span>
              </el-badge>
            </template>
            <div class="content">
              <div class="base_details_title">优惠区域</div>
              <div class="base_details_content_second">
                <el-form :model="basicForm" :disabled="readOnly" :rules="basicRules" label-width="100px"
                  class="base_details_form">
                  <el-form-item label="产品类型" prop="limitBusiType">
                    <el-radio-group v-model="basicForm.limitBusiType" @change="limitBusiTypeChange">
                      <el-radio v-for="(item, index) in typeOptions" :key="index" :label="item.value">{{ item.label }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
              <div class="base_details_title_button">
                <div class="tb_title">产品设置<b></b></div>
                <el-button @click="addProduct" type="primary" v-if="!readOnly">添加产品</el-button>
              </div>

              <div class="base_details_content_second">
                <ProductTable type="show" ref="showTableRef" :typeKey="showTypeKey" :codeList="basicForm.codeList">
                </ProductTable>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-main>
      <el-footer>
        <el-button @click="route.go(-1)" v-show="activeName === 'basic'">取消</el-button>
        <el-button @click="tabChange('spec')" v-show="activeName === 'basic'" type="primary">下一步</el-button>
        <el-button @click="tabChange('basic')" v-show="activeName === 'spec'">上一步</el-button>
        <el-button @click="saveForm(0)" v-show="activeName === 'spec'" type="primary" v-if="!readOnly">保存
        </el-button>
        <el-button @click="saveForm(1)" v-show="activeName === 'spec'" type="primary" v-if="!readOnly">保存并发布</el-button>
      </el-footer>
    </el-container>
    <el-drawer custom-class="base_drawer" v-model="drawer" :close-on-click-modal="false" title="添加产品"
      :with-header="true" :size="720">
      <ProductTable type="add" ref="addTableRef" :typeKey="typeKey"></ProductTable>
      <template #footer>
        <div>
          <el-button @click="closeDrawer">取消</el-button>
          <el-button @click="saveProduct" type="primary">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { $msg } from "@ui/msg";
import BackTitleView from "@com/BackTitleView.vue";
import UploadPicture from "@com/upload/UploadPicture.vue";
import ProductTable from "@com/marketing/ProductTable.vue";
import { ref, reactive } from "vue";
import $ from "@util/base";
import api from "@api/promotions"
import useRoute from "@util/router";

const route = useRoute();

const urlQuery = route.query();
const readOnly = urlQuery.type == "show";
var title = "活动详情";
switch (urlQuery.type) {
  case "show":
    title = "活动详情";
    getDetails()
    break;
  case "add":
    title = "新增活动";
    break;
  case "modify":
    title = "修改活动";
    getDetails()
    break;
}

const moneyTypeOptions = [
  {
    label: "满减",
    value: "1010001",
  },
  {
    label: "折扣",
    value: "1010002",
  },
];

const typeOptions = [
  {
    label: "商品",
    value: "1003001",
    key: "goods",
  },
  {
    label: "旅行",
    value: "1003002",
    key: "travel",
  },
  {
    label: "酒店",
    value: "1003003",
    key: "hotel",
  },
];

const basicForm = ref({
  name: null,
  date: [],
  mainPic: [],
  itemPic:[],
  intro: null,
  moneyType: "1010001",
  moneyOff: {
    limitMoney: null,
    money: null,
  },
  discountMoney: null,

  limitBusiType: "1003001",
  codeList: [],
});

const addTableRef = ref(null);
const showTableRef = ref(null);
const typeKey = ref(null);
const showTypeKey = ref(null);

const drawer = ref(false);
function openDrawer() {
  drawer.value = true;
}
function closeDrawer() {
  drawer.value = false;
}

function limitBusiTypeChange() {
  console.log("清空");
  showTableRef.value.empty();
  basicForm.value.codeList = [];
}

function addProduct() {
  let value = basicForm.value.limitBusiType;
  let index = typeOptions.findIndex((e) => {
    return e.value === value;
  });
  typeKey.value = typeOptions[index].key;
  openDrawer();
}

function saveProduct() {
  let data = addTableRef.value.getSelection();
  if ($.isEmpty(data)) {
    $msg.error("请勾选需要添加的产品");
  } else {
    closeDrawer();
    showTypeKey.value = typeKey.value;
    basicForm.value.codeList = data;
  }
}

const checkMoneyOff = (rule, value, callback) => {
  if (
    $.isNull(basicForm.value.moneyOff.limitMoney) ||
    $.isNull(basicForm.value.moneyOff.money)
  ) {
    callback(new Error("请输入优惠内容"));
  }
  if (parseFloat(basicForm.value.moneyOff.money) > parseFloat(basicForm.value.moneyOff.limitMoney)) {
    callback(new Error("立减金额必须小于消费金额"));
  }
  return true;
};

const basicRules = {
  name: [
    {
      required: true,
      message: "请输入活动名称",
      trigger: "blur",
    },
  ],
  date: [
    {
      required: true,
      type: "array",
      message: "请选择活动时间",
      trigger: "change",
    },
  ],
  mainPic: [
    {
      required: true,
      message: "请上传活动封面",
      trigger: "blur",
    },
  ],
  itemPic: [
    {
      required: true,
      message: "请上传活动列表图",
      trigger: "blur",
    },
  ],
  intro: [
    {
      required: true,
      message: "请输入活动简介",
      trigger: "blur",
    },
  ],
  moneyType: [
    {
      required: true,
      message: "请选择优惠形式",
      trigger: "change",
    },
  ],
  moneyOff: [
    {
      required: true,
      validator: checkMoneyOff,
      trigger: "blur",
    },
  ],
  discountMoney: [
    {
      required: true,
      message: "请输入优惠内容",
      trigger: "blur",
    },
  ],
  limitBusiType: [
    {
      required: true,
      message: "请选择产品类型",
      trigger: "change",
    },
  ],
};

const setDisableDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7;  //如果没有后面的-8.64e7就是不可以选择今天的
}

const activeName = ref("basic");

function tabChange(active) {
  if (active === "spec") {
    checkBasic(active)
  } else {
    activeName.value = active;
  }
}

const basicFormRef = ref(null);
const discountsFormRef = ref(null);

function checkBasic(active) {
  let check = [false, false];
  let p1 = basicFormRef.value.validate((valid) => {
    if (valid) {
      check[0] = true;
    } else {
      check[0] = false;
    }
  });
  let p2 = discountsFormRef.value.validate((valid) => {
    if (valid) {
      check[1] = true;
    } else {
      check[1] = false;
    }
  });
  Promise.all([p1, p2]).then(() => {
    if (check.every(function (e) {
      return e;
    })) {
      activeName.value = active;
    }
  })
}

function checkProduct() {
  if ($.isNotEmpty(basicForm.value.codeList)) {
    return true
  } else {
    $msg.error("请添加产品");
    return false
  }
}

function saveForm(type) {
  if (!checkBasic() && !checkProduct()) {
    return
  }
  $.handleCRU(route.query().type, {
    add: () => { addData(type) },
    modify: () => { modifyData(type) }
  })
}

function addData(type) {
  api.add(type, basicForm.value, () => {
    $msg.succ("新增成功");
    back()
  })
}
function modifyData(type) {
  api.update(urlQuery.code, type, basicForm.value, () => {
    $msg.succ("修改成功");
    back()
  })
}

function getDetails() {
  api.details(urlQuery.code, val => {
    basicForm.value = val
    let index = typeOptions.findIndex(e => e.value == val.limitBusiType)
    showTypeKey.value = typeOptions[index].key
  })
}

function back() {
  route.go(-1)
}
</script>

<style lang="scss" scoped>
.promotions_details {
  height: 100%;

  .money_box {
    span {
      margin: 0 10px;

      &:nth-child(1) {
        margin-left: 0;
      }
    }

    .el-input {
      width: 120px !important;
    }
  }
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}

::v-deep input[type="number"] {
  -moz-appearance: textfield !important;
}
</style>
